package com.yjzx.util.common.util.BeanUtils;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author guozhi
 * @date 2025/1/24
 * @description MethodHandlesInterface
 */
public interface MethodHandlesInterface {
    default Map<Method, MethodHandle> toMethodHandle(Method... methodNames) throws NoSuchMethodException, IllegalAccessException {
        HashMap<Method, MethodHandle> map = new HashMap<>(8);
        MethodHandles.Lookup lookup = MethodHandles.lookup();
        for (Method method : methodNames) {
            MethodHandle handle = lookup.unreflect(method);
            map.put(method, handle);
        }
        return map;
    }

    default Map<String, MethodHandle> toFieldSetMethodHandle() {
        HashMap<String, MethodHandle> map = new HashMap<>();
        Field[] fields = this.getClass().getDeclaredFields();
        MethodHandles.Lookup lookup = MethodHandles.lookup();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                MethodHandle handle = lookup.unreflectSetter(field);
                map.put(field.getName(), handle);
            } catch (IllegalAccessException ignored) {
            }
        }
        return map;
    }

    default Map<String, MethodHandle> toFieldGetMethodHandle() {
        HashMap<String, MethodHandle> map = new HashMap<>();
        Field[] fields = this.getClass().getDeclaredFields();
        MethodHandles.Lookup lookup = MethodHandles.lookup();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                MethodHandle handle = lookup.unreflectGetter(field);
                map.put(field.getName(), handle);
            } catch (IllegalAccessException ignored) {
            }
        }
        return map;
    }
}
